package Easy链表求和;

import org.testng.annotations.Test;

public class Solution {
    public ListNode addTwoNumbers1(ListNode l1, ListNode l2){

        ListNode head = null, tail = null;
        int carry = 0;
        while (l1 != null || l2 != null) {
            int n1 = l1 != null ? l1.val : 0;
            int n2 = l2 != null ? l2.val : 0;
            int sum = n1 + n2 + carry;
            if (head == null) {
                head = tail = new ListNode(sum % 10);
            }
            else {
                tail.next = new ListNode(sum % 10);
                tail = tail.next;
            }

            carry = sum / 10;

            if (l1 != null) {
                l1 = l1.next;
            }
            if (l2 != null) {
                l2 = l2.next;
            }
        }

        if (carry > 0) {
            tail.next = new ListNode(carry);
        }
        return head;
    }
    public ListNode addTwoNumbers2(ListNode l1, ListNode l2) {

        ListNode q1 = l1;
        ListNode q2 = l2;

        ListNode T1 = new ListNode();
        ListNode t1 = T1;
        Integer sum;
        Integer sum1 = 0;
        Integer sum2 = 0;

        int max;
        int a;

        for (int i = 0; q1!=null; i++) {
            sum1 = sum1+q1.val*(int)Math.pow(10,i);
            q1 = q1.next;
        }
        for (int i = 0; q2!=null; i++) {
            sum2 = sum2+q2.val*(int)Math.pow(10,i);
            q2 = q2.next;
        }
        sum = sum1+sum2;
        System.out.println(sum);
        max = (int)Math.log10(sum);

        for (int i = 0; i < max; i++) {
            a = sum %10;
            sum = sum /10;
            T1.val = a;
            T1.next = new ListNode(0,null);
            T1 = T1.next;
        }

        a = sum %10;
        T1.val = a;

        return t1;
    }

    public ListNode addTwoNumbers(ListNode l1, ListNode l2){
        ListNode head = null, tail = null;
        int carry = 0;
        while(l1 != null || l2 != null){
            int n1 = l1 != null ? l1.val : 0;
            int n2 = l2 != null ? l2.val : 0;
            int sum = n1 + n2 + carry;
            if (head == null)
                head = tail = new ListNode(sum % 10);
            else{
                tail.next = new ListNode(sum % 10);
                tail = tail.next;
            }

            carry = sum / 10;
            if (l1 != null) {
                l1 = l1.next;
            }
            if (l2 != null) {
                l2 = l2.next;
            }
        }
        if(carry != 0)
            tail.next = new ListNode(carry);
        return head;
    }

}
